import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/mood_provider.dart';
import '../models/mood_record.dart';
import '../constants/app_theme.dart';
import '../constants/app_strings.dart';
import '../constants/app_routes.dart';
import '../widgets/mood_card.dart';
import '../widgets/custom_app_bar.dart';
import '../widgets/calendar_widget.dart';
import '../widgets/filter_widget.dart';

/// 历史记录页面
/// 提供日历视图和列表浏览功能，支持按日期筛选和搜索
class HistoryScreen extends StatefulWidget {
  const HistoryScreen({super.key});

  @override
  State<HistoryScreen> createState() => _HistoryScreenState();
}

class _HistoryScreenState extends State<HistoryScreen>
    with TickerProviderStateMixin {
  // 控制器
  late TabController _tabController;
  late TextEditingController _searchController;
  late ScrollController _listScrollController;
  
  // 状态变量
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  List<MoodRecord> _filteredRecords = [];
  bool _isSearching = false;
  bool _isLoading = false;
  String _searchQuery = '';
  
  // 分页相关
  bool _hasMoreData = true;
  bool _isLoadingMore = false;
  
  // 筛选相关
  FilterOptions _filterOptions = FilterOptions();
  bool _showFilterPanel = false;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _searchController = TextEditingController();
    _listScrollController = ScrollController();
    
    // 监听滚动事件，实现分页加载
    _listScrollController.addListener(_onScroll);
    
    // 初始化数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadInitialData();
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _searchController.dispose();
    _listScrollController.dispose();
    super.dispose();
  }

  /// 加载初始数据
  Future<void> _loadInitialData() async {
    if (!mounted) return;
    
    setState(() {
      _isLoading = true;
    });
    
    try {
      final provider = Provider.of<MoodProvider>(context, listen: false);
      await provider.initialize();
      if (mounted) {
        _updateFilteredRecords();
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('加载数据失败：${e.toString()}');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  /// 监听滚动事件，实现分页加载
  void _onScroll() {
    if (_listScrollController.position.pixels >=
        _listScrollController.position.maxScrollExtent - 200) {
      _loadMoreData();
    }
  }

  /// 加载更多数据
  Future<void> _loadMoreData() async {
    if (_isLoadingMore || !_hasMoreData || !mounted) return;
    
    setState(() {
      _isLoadingMore = true;
    });
    
    try {
      // 暂时禁用分页加载功能
      _hasMoreData = false;
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('加载更多数据失败');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoadingMore = false;
        });
      }
    }
  }

  /// 更新筛选后的记录
  void _updateFilteredRecords() {
    final provider = Provider.of<MoodProvider>(context, listen: false);
    List<MoodRecord> records = provider.records;
    
    // 如果有选中的日期，按日期筛选
    if (_selectedDay != null) {
      records = records.where((record) {
        return _isSameDay(record.createdAt, _selectedDay!);
      }).toList();
    }
    
    // 如果有搜索查询，按内容筛选
    if (_searchQuery.isNotEmpty) {
      records = records.where((record) {
        return (record.content?.toLowerCase() ?? '').contains(_searchQuery.toLowerCase()) ||
               record.tags.any((tag) => tag.toLowerCase().contains(_searchQuery.toLowerCase()));
      }).toList();
    }
    
    // 应用高级筛选
    records = FilterApplier.applyFilters(records, _filterOptions);
    
    setState(() {
      _filteredRecords = records;
    });
  }

  /// 判断两个日期是否为同一天
  bool _isSameDay(DateTime a, DateTime b) {
    return a.year == b.year && a.month == b.month && a.day == b.day;
  }

  /// 搜索记录
  void _searchRecords(String query) {
    setState(() {
      _searchQuery = query;
      _isSearching = query.isNotEmpty;
    });
    _updateFilteredRecords();
  }

  /// 清除搜索
  void _clearSearch() {
    _searchController.clear();
    setState(() {
      _searchQuery = '';
      _isSearching = false;
    });
    _updateFilteredRecords();
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppTheme.errorColor,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  /// 显示成功提示
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.backgroundColor,
      appBar: _buildAppBar(),
      body: Column(
        children: [
          _buildSearchBar(),
          if (_showFilterPanel) _buildFilterPanel(),
          _buildTabBar(),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildCalendarView(),
                _buildListView(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return CustomAppBar(
      title: AppStrings.get('history_title'),
      actions: [
        IconButton(
          icon: const Icon(Icons.today),
          onPressed: () {
            setState(() {
              _focusedDay = DateTime.now();
              _selectedDay = DateTime.now();
            });
            _updateFilteredRecords();
          },
          tooltip: '回到今天',
        ),
        IconButton(
          icon: Icon(
            Icons.filter_list,
            color: _filterOptions.hasActiveFilters 
                ? AppTheme.primaryColor 
                : null,
          ),
          onPressed: _toggleFilter,
          tooltip: '筛选',
        ),
      ],
    );
  }

  /// 构建搜索栏
  Widget _buildSearchBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      color: AppTheme.surfaceColor,
      child: TextField(
        controller: _searchController,
        decoration: InputDecoration(
          hintText: '搜索日记内容或标签...',
          prefixIcon: const Icon(Icons.search),
          suffixIcon: _isSearching
              ? IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: _clearSearch,
                )
              : null,
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide.none,
          ),
          filled: true,
          fillColor: AppTheme.backgroundColor,
        ),
        onChanged: _searchRecords,
      ),
    );
  }

  /// 构建标签栏
  Widget _buildTabBar() {
    return Container(
      color: AppTheme.surfaceColor,
      child: TabBar(
        controller: _tabController,
        tabs: const [
          Tab(
            icon: Icon(Icons.calendar_month),
            text: '日历视图',
          ),
          Tab(
            icon: Icon(Icons.list),
            text: '列表视图',
          ),
        ],
        labelColor: AppTheme.primaryColor,
        unselectedLabelColor: AppTheme.textSecondaryColor,
        indicatorColor: AppTheme.primaryColor,
      ),
    );
  }

  /// 构建日历视图
  Widget _buildCalendarView() {
    return Consumer<MoodProvider>(
      builder: (context, provider, child) {
        if (_isLoading) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        
        return Column(
          children: [
            CalendarWidget(
              records: provider.records,
              initialSelectedDay: _selectedDay,
              initialFocusedDay: _focusedDay,
              onDaySelected: (selectedDay, focusedDay) {
                setState(() {
                  _selectedDay = selectedDay;
                  _focusedDay = focusedDay;
                });
                _updateFilteredRecords();
              },
            ),
            Expanded(
              child: _buildSelectedDayRecords(),
            ),
          ],
        );
      },
    );
  }

  /// 构建选中日期的记录
  Widget _buildSelectedDayRecords() {
    if (_selectedDay == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.calendar_today,
              size: 64,
              color: AppTheme.textSecondaryColor.withValues(alpha: 0.5),
            ),
            const SizedBox(height: 16),
            Text(
              '选择一个日期查看记录',
              style: TextStyle(
                fontSize: 16,
                color: AppTheme.textSecondaryColor,
              ),
            ),
          ],
        ),
      );
    }
    
    if (_filteredRecords.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.mood_bad,
              size: 64,
              color: AppTheme.textSecondaryColor.withValues(alpha: 0.5),
            ),
            const SizedBox(height: 16),
            Text(
              '这一天还没有记录',
              style: TextStyle(
                fontSize: 16,
                color: AppTheme.textSecondaryColor,
              ),
            ),
            const SizedBox(height: 8),
            TextButton(
              onPressed: () {
                AppRoutes.navigateTo(context, AppRoutes.record);
              },
              child: const Text('添加记录'),
            ),
          ],
        ),
      );
    }
    
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _filteredRecords.length,
      itemBuilder: (context, index) {
        final record = _filteredRecords[index];
        return Padding(
          padding: const EdgeInsets.only(bottom: 12),
          child: MoodCard(
            record: record,
            onTap: () => _navigateToDetail(record),
            onEdit: () => _navigateToEdit(record),
            onDelete: () => _deleteRecord(record),
          ),
        );
      },
    );
  }

  /// 构建列表视图
  Widget _buildListView() {
    return Consumer<MoodProvider>(
      builder: (context, provider, child) {
        if (_isLoading) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        
        if (_filteredRecords.isEmpty) {
          return _buildEmptyState();
        }
        
        return RefreshIndicator(
          onRefresh: _loadInitialData,
          child: ListView.builder(
            controller: _listScrollController,
            padding: const EdgeInsets.all(16),
            itemCount: _filteredRecords.length + (_isLoadingMore ? 1 : 0),
            itemBuilder: (context, index) {
              if (index == _filteredRecords.length) {
                return const Center(
                  child: Padding(
                    padding: EdgeInsets.all(16),
                    child: CircularProgressIndicator(),
                  ),
                );
              }
              
              final record = _filteredRecords[index];
              return Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: MoodCard(
                  record: record,
                  onTap: () => _navigateToDetail(record),
                  onEdit: () => _navigateToEdit(record),
                  onDelete: () => _deleteRecord(record),
                ),
              );
            },
          ),
        );
      },
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            _isSearching ? Icons.search_off : Icons.mood_bad,
            size: 64,
            color: AppTheme.textSecondaryColor.withValues(alpha: 0.5),
          ),
          const SizedBox(height: 16),
          Text(
            _isSearching ? '没有找到匹配的记录' : '还没有任何记录',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w500,
              color: AppTheme.textSecondaryColor,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            _isSearching ? '尝试使用其他关键词搜索' : '开始记录你的第一个心情吧',
            style: TextStyle(
              fontSize: 14,
              color: AppTheme.textSecondaryColor,
            ),
          ),
          if (!_isSearching) ...[
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: () {
                AppRoutes.navigateTo(context, AppRoutes.record);
              },
              icon: const Icon(Icons.add),
              label: const Text('添加记录'),
              style: ElevatedButton.styleFrom(
                backgroundColor: AppTheme.primaryColor,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(
                  horizontal: 24,
                  vertical: 12,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 切换筛选面板
  void _toggleFilter() {
    setState(() {
      _showFilterPanel = !_showFilterPanel;
    });
  }
  
  /// 构建筛选面板
  Widget _buildFilterPanel() {
    return Consumer<MoodProvider>(
      builder: (context, moodProvider, child) {
        // 获取所有可用的标签
        final allTags = <String>{};
        for (final record in moodProvider.records) {
          allTags.addAll(record.tags);
        }
        
        return Container(
          margin: const EdgeInsets.all(16),
          child: FilterWidget(
            filterOptions: _filterOptions,
            availableTags: allTags.toList()..sort(),
            onFilterChanged: (options) {
              setState(() {
                _filterOptions = options;
              });
              _updateFilteredRecords();
            },
          ),
        );
      },
    );
  }
  


  /// 导航到详情页
  void _navigateToDetail(MoodRecord record) {
    if (record.id != null) {
      AppRoutes.navigateToMoodDetail(context, record.id.toString());
    }
  }

  /// 导航到编辑页
  void _navigateToEdit(MoodRecord record) {
    if (record.id != null) {
      AppRoutes.navigateToEditRecord(context, record.id.toString());
    }
  }

  /// 删除记录
  Future<void> _deleteRecord(MoodRecord record) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这条记录吗？此操作无法撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(
              foregroundColor: AppTheme.errorColor,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );
    
    if (confirmed == true && mounted) {
      try {
        final provider = Provider.of<MoodProvider>(context, listen: false);
        if (record.id != null) {
          await provider.deleteRecord(record.id.toString());
        }
        if (mounted) {
          _updateFilteredRecords();
          _showSuccessSnackBar('记录已删除');
        }
      } catch (e) {
        if (mounted) {
          _showErrorSnackBar('删除失败：${e.toString()}');
        }
      }
    }
  }
}